package service

import (
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"mt-server/basic/config"
	__ "mt-server/basic/proto"
	"mt-server/handler/model"
	"time"

	"github.com/go-redis/redis/v8"
)

// 商家订单处理
func (s *Server) MerchantStatus(_ context.Context, in *__.MerchantStatusReq) (*__.MerchantStatusResp, error) {
	var or model.Order
	or = model.Order{
		Id:             uint64(in.Id),
		MerchantStatus: in.MerchantStatus,
	}
	err := or.UpOrder()
	if err != nil {
		return &__.MerchantStatusResp{
			Msg:  "商家订单处理失败",
			Code: 200,
		}, nil
	}

	return &__.MerchantStatusResp{
		Msg:  "商家订单处理成功",
		Code: 200,
	}, nil
}

// 骑手订单处理
func (s *Server) RiderStatus(_ context.Context, in *__.RiderStatusReq) (*__.RiderStatusResp, error) {

	var or model.Order
	or = model.Order{
		Id:          uint64(in.Id),
		RiderStatus: in.RiderStatus,
	}

	var ri model.Rider
	err := ri.FindRider()
	if err != nil {
		return nil, err
	}
	rankKey := "simple_rank_demo"

	OrderTotal := []struct {
		ID    float64
		Score float64
	}{{}}

	for _, val := range OrderTotal {
		err = config.Rdb.ZAdd(config.Ctx, rankKey, &redis.Z{
			Score:  val.ID,
			Member: val.Score,
		}).Err()
		if err != nil {
			fmt.Printf("添加用户到排行榜失败：%v\n", err)
		}
	}
	fmt.Println("=== 所有用户已添加到排行榜 ===")

	err = or.UpOrder()
	if err != nil {
		return &__.RiderStatusResp{
			Msg:  "骑手订单处理失败",
			Code: 500,
		}, nil
	}

	return &__.RiderStatusResp{
		Msg:  "骑手订单处理成功",
		Code: 200,
	}, nil
}

// 用户订单状态查看
func (s *Server) UserLock(_ context.Context, in *__.UserLockReq) (*__.UserLockResp, error) {
	var or model.Order
	or = model.Order{
		UserId: or.UserId,
	}
	//err := or.FindOrder()
	//if err != nil {
	//	return nil, err
	//}

	//var good model.Goods
	//err = good.FindGoods()
	//if err != nil {
	//	return nil, err
	//}

	//菜单redis
	userData := map[string]string{
		"Id":   "1",
		"Name": "扬州炒饭",
	}

	// 将用户数据序列化为JSON
	orderJSON, err := json.Marshal(userData)
	if err != nil {
		errors.New("序列化失败")
	}

	//键名
	key_order := "goods_number"

	//存入redis
	config.Rdb.Set(config.Ctx, key_order, orderJSON, 24*time.Hour)

	return &__.UserLockResp{
		Amount:         10.50,
		Address:        "上海全栈",
		UserId:         1,
		MerchantStatus: "1",
		RiderStatus:    "1",
	}, nil
}
